package obecto.container
{
	import flash.geom.Rectangle;
	
	import obecto.core.FLContainer;
	import obecto.event.FLEvent;
	
	public class ClippingContainer extends FLContainer
	{
		[Bindable]
		override public function set width(value : Number) : void
		{
			clippingRect.width = value;
			if (initialized)
			{
				updateScrollRect();
			}
			else
			{
				initializationScrollRectChanged = true;
			}
		}
		override public function get width() : Number
		{
			return clippingRect.width;
		}
		
		[Bindable]
		override public function set height(value : Number) : void
		{
			clippingRect.height = value;
			if (initialized)
			{
				updateScrollRect();
			}
			else
			{
				initializationScrollRectChanged = true;
			}
		}
		override public function get height() : Number
		{
			return clippingRect.height;
		}
		
		[Bindable]
		public function set scrollX(value : Number) : void
		{
			clippingRect.x = value;
			if (initialized)
			{
				updateScrollRect();
			}
			else
			{
				initializationScrollRectChanged = true;
			}
		}
		public function get scrollX() : Number
		{
			return clippingRect.x;
		}
		
		[Bindable]
		public function set scrollY(value : Number) : void
		{
			clippingRect.y = value;
			if (initialized)
			{
				updateScrollRect();
			}
			else
			{
				initializationScrollRectChanged = true;
			}
		}
		public function get scrollY() : Number
		{
			return clippingRect.y;
		}
		
		protected var clippingRect : Rectangle = new Rectangle();
		protected var originalRect : Rectangle = new Rectangle();;
		protected var initializationScrollRectChanged : Boolean = false;
		
		public function ClippingContainer()
		{
			super();
			
			// initially the component is invisible to avoid any visual glitches with the lazy setting of the scrollRect:
			visible = false;
			
			addEventListener(FLEvent.CREATION_COMPLETE, handleCreationComplete);
		}
		
		public function updateScrollRect() : void 
		{
			clippingRect.x = Math.round(clippingRect.x);
			clippingRect.y = Math.round(clippingRect.y);
			clippingRect.width = Math.round(clippingRect.width);
			clippingRect.height = Math.round(clippingRect.height);
			
			scrollRect = clippingRect;
		}
		
		protected function handleCreationComplete(e : FLEvent) : void 
		{
			updateScrollRect();
			visible = true;
		}
		
	}
}